#ifndef __IOMANGER_H__
#define __IOMANGER_H__

#include "scheduler.h"
#include "timer.h"

namespace sylar
{

class IOManger : public sylar::Scheduler, public sylar::TimerManger
{
public:
    using ptr = std::shared_ptr<IOManger>;
    using RWMutexType = RWMutex;

    enum Event
    {
        NONE    = 0x0,
        READ    = 0x1,  // EPOLLIN
        WRITE   = 0x4   // EPOLLOUT
    };

private:
    // Socket事件上线
    struct FdContext
    {
        using MutexType = Mutex;
        struct EventContext
        {
            Scheduler* scheduler = nullptr; // 事件执行调度器
            Fiber::ptr fiber = nullptr;     // 事件的协程
            std::function<void(void)> cb = nullptr;   // 事件的回调
        };

        EventContext& getEventContext(Event event);

        void resetContext(EventContext& context);

        void triggerEvent(Event event);

        int fd;             // 事件关联句柄
        EventContext read; //读事件
        EventContext write; // 写事件
        Event events = NONE;      // 已经注册的事件
        MutexType mutex;
    };

public:
    IOManger(size_t threads = 1, bool use_coller = true, const std::string& name = "");

    ~IOManger();

    //0成功  -1失败
    int addEvent(int fd, Event event, std::function<void(void)> cb = nullptr);

    bool delEvent(int fd, Event event);

    bool cancelEvent(int fd, Event event);

    bool cancelAll(int fd);

    static IOManger* GetThis(); 

protected:

    // 通知协程调度器有任务了
    void tickle() override;

    // 停止操作 做一些状态设置？？？？？
    bool stopping() override;
    bool stopping(uint64_t& timeout);
    // 没有任务做时调用 由具体模块实现，比如释放线程 sleep等等
    // 比如网络epoll 时 epoll_wait
    void idle() override;

    void contextResize(size_t size);

    virtual void onTimerInserFront() override;

private:
    int m_epfd = 0;

    int m_tickFds[2];   // pipe 文件句柄

    std::atomic<size_t> m_pendingEventCount = {0};
    RWMutex m_mutex;

    std::vector<FdContext*> m_fdContext; 
};



}


#endif